import 'dart:convert';
import 'dart:io';

import 'package:crypto/crypto.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:study_demo/base/BaseController.dart';

class Md5HelperController extends BaseController {
  final result = ''.obs;
  final filePath = ''.obs;

  TextEditingController _textEditingController = TextEditingController();

  TextEditingController get textEditingController => _textEditingController;

  TextEditingController _resultEditingController = TextEditingController();

  TextEditingController get resultEditingController => _resultEditingController;

  encodeString(int type) {
    String s = _textEditingController.text.trim().toString();
    final bytes = utf8.encode(s);
    switch (type) {
      case 1:
        result.value = md5.convert(bytes).toString();
        break;
      case 2:
        result.value = sha1.convert(bytes).toString();
        break;
      case 3:
        result.value = sha256.convert(bytes).toString();
        break;
    }

    _resultEditingController.text = result.value;
  }

  chooseFile() async {
    final result = await FilePicker.platform.pickFiles();
    if (result != null) {
      final path = result.files.single.path;
      filePath.value = path!;
    }
  }

  encodeFile(int type) async {
    File file = File(filePath.value);
    final bytes = await file.readAsBytes();
    switch (type) {
      case 1:
        result.value = md5.convert(bytes).toString();
        break;
      case 2:
        result.value = sha1.convert(bytes).toString();
        break;
      case 3:
        result.value = sha256.convert(bytes).toString();
        break;
    }

    _resultEditingController.text = result.value;
  }

  encode(int type) {
    String s = _textEditingController.text.trim().toString();
    if (s.isNotEmpty) {
      encodeString(type);
    } else if (filePath.isNotEmpty) {
      encodeFile(type);
    }
  }
}
